package com.micro.common.service.web.service.open;

import cn.hutool.core.bean.BeanUtil;
import com.micro.common.service.orm.entity.TaskPo;
import com.micro.common.service.orm.entity.TaskTemplatePo;
import com.micro.common.service.orm.enums.TaskStatus;
import com.micro.common.service.orm.service.TaskServiceImpl;
import com.micro.common.service.orm.service.TaskTemplateServiceImpl;
import com.micro.common.service.web.client.api.TaskOpenApi;
import com.micro.common.service.web.client.domain.req.task.TaskAddReq;
import com.micro.common.service.web.client.domain.req.task.TaskEditReq;
import com.micro.framework.starter.common.data.enums.YesNoEnum;
import com.micro.framework.starter.common.data.result.Result;
import com.micro.framework.starter.common.utils.MicroStringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

@Slf4j
@Service
public class TaskOpenApiService implements TaskOpenApi {
    @Resource
    private TaskServiceImpl taskService;
    @Resource
    private TaskTemplateServiceImpl taskTemplateService;

    @Override
    public Result<Void> taskAdd(TaskAddReq req) {
        TaskTemplatePo templatePo = taskTemplateService.getBaseMapper().findByType(req.getTaskType());
        if (Objects.isNull(templatePo) || !YesNoEnum.YES.getCode().equals(templatePo.getStatus())) {
            return Result.fail("模板不存在或已禁用");
        }
        TaskPo taskPo = BeanUtil.copyProperties(req, TaskPo.class);
        taskPo.setTaskLevel(templatePo.getTaskLevel());
        taskPo.setTaskTitle(MicroStringUtil.textRepalce(templatePo.getTaskTitle(), req.getMapParam()));
        taskPo.setTaskContent(MicroStringUtil.textRepalce(templatePo.getContent(),  req.getMapParam()));
        taskPo.setTaskStatus(TaskStatus.WAIT.getCode());
        taskService.save(taskPo);
        return Result.success();
    }

    @Override
    public Result<Void> taskStatusEdit(TaskEditReq req) {
        TaskPo taskPo = new TaskPo();
        taskPo.setBusinessId(req.getBusinessId());
        taskPo.setTaskStatus(req.getTaskStatus());
        taskPo.setUpdater(req.getUpdater());
        taskPo.setUpdaterName(req.getUpdaterName());
        taskService.getBaseMapper().updateStatusByBusinessId(taskPo);
        return Result.success();
    }
}
